package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.CartMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * 下单: 从购物车中将数据取出来,分别保存到订单表和订单明细表,保存成功后需要将购物车数据删了
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)  // 解决事务问题:执行结果前后一致
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1 参数校验
        //地址是否存在校验
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException("配送地址不能为空");
        }
        //当前用户是否登录
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new OrderBusinessException("下单必须要求登录");
        }

        //2 查询我的购物车
        List<ShoppingCart> cartList = cartMapper.findByQuery(ShoppingCart.builder().userId(userId).build());
        //3 如果购物车数据为空则抛异常
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException("购物车为空,不能下单");
        }
        //4 保存订单数据到订单表 1条
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //** 订单编号 支付使用
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //待付款
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        //微信支付
        orders.setPayMethod(1);
        //未支付
        orders.setPayStatus(1);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());
        //预计送达时间
        orders.setEstimatedDeliveryTime(LocalDateTime.now().minusHours(1));
        orders.setPackAmount(3);
        orders.setTablewareNumber(1);
        orders.setTablewareStatus(1);

        orderMapper.insert(orders);


        //5 保存订单明细数据到订单明细中 n条
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            //*** 订单id: 标识订单和订单明细之间 1对多关系
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        //执行批量保存订单明细
        orderDetailMapper.insertBatch(orderDetails);

        //6 清理购物车
        cartMapper.deleteByUserId(userId);

        //7 封装结果并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .build();
        return orderSubmitVO;
    }
}
